package com.miqtech.master.wyrecorder.ui;

/**
 * Created by arvin on 2016/12/23.
 */

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.WYRecorderApp;
import com.miqtech.master.wyrecorder.annotations.LayoutId;
import com.miqtech.master.wyrecorder.annotations.Title;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.constants.Constants;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.nim.NIMHelper;
import com.miqtech.master.wyrecorder.user.UserProxy;
import com.miqtech.master.wyrecorder.utils.Utils;
import com.miqtech.master.wyrecorder.utils.imageloader.AsyncImage;
import com.miqtech.master.wyrecorder.widget.MyAlertView;
import com.miqtech.master.wyrecorder.widget.PhoneTextWatcher;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


@LayoutId(R.layout.activity_fast_login_layout)
@Title(title = "快捷登录")
public class FastLoginActivity extends BaseAppCompatActivity implements MyAlertView.VerificationCodeDialogAction, PhoneTextWatcher.ContextListener {
    @BindView(R.id.rlLoginPhone)
    RelativeLayout rlLoginPhone;
    @BindView(R.id.etLoginPhone)
    EditText etLoginPhone;
    @BindView(R.id.ivClear)
    ImageView ivClear;
    @BindView(R.id.etLoginCode)
    EditText etLoginCode;
    @BindView(R.id.tvGetCode)
    TextView tvGetCode;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.tvLoginProtocol)
    TextView tvLoginProtocol;
    @BindView(R.id.tvAccountErrorTips)
    TextView tvAccountErrorTips;
    @BindView(R.id.llLoginCode)
    LinearLayout llLoginCode;
    @BindView(R.id.mainHeader)
    LinearLayout mainHeader;
    @BindView(R.id.llParent)
    LinearLayout llParent;
    private PhoneTextWatcher watcher;
    private String phoneNum;
    private String password;
    private boolean isNeedServiceCode = false;//是否需要服务器验证码
    private MyAlertView dialog;
    private Timer timer;
    private MyTimerTask task;
    private int totalTime = 60;
    private MyHandler myHandler;
    private String toObtain;
    private String imputServicerCode;//服务器验证码
    private boolean isPasswordFormatRight = false;
    private View dialogRlServiceCode;
    private View dialogTvYes;
    private View dialogIvServiceCode;
    private View dialogEtServiceCode;
    private Animation animiationShaking;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        initView();
        setListener();
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        toObtain = getResources().getString(R.string.to_obtain);
        animiationShaking = AnimationUtils.loadAnimation(this, R.anim.shaking);
        mainHeader.setBackgroundColor(getResources().getColor(R.color.transparent));
        Utils.setFontDiffrentColor(getString(R.string.fast_login_protocol), 7, getString(R.string.fast_login_protocol).length(), tvLoginProtocol, R.color.bar_text_selected);
        setLoginBtn(false);
        tvGetCode.setEnabled(false);
    }

    private void setListener() {
        watcher = new PhoneTextWatcher(etLoginPhone, ivClear, getResources().getString(R.string.please_imput_phone), this);
        watcher.isMobileFormatJudge(false);
        etLoginPhone.addTextChangedListener(watcher);
        etLoginCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (etLoginCode.getText().length() >= 6) {
                        isPasswordFormatRight = true;
                        if (watcher.isFullPhone()) {
                            setLoginBtn(true);
                        } else {
                            setLoginBtn(false);
                        }
                    } else {
                        isPasswordFormatRight = false;
                        setLoginBtn(false);
                    }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etLoginPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && (!watcher.isFullPhone() || !etLoginPhone.getText().toString().replaceAll("\\s*", "").matches(Constants.PHONE_FORMAT))) {
                    setPhoneTipsVisible(true);
                } else {
                    setPhoneTipsVisible(false);
                }
            }
        });
        etLoginCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && etLoginCode.getText().toString().length() < 6) {
                    setCodeTipsVisible(true);
                } else {
                    setCodeTipsVisible(false);
                }
            }
        });
    }

    /**
     *   设置手机号码错误提示 并更改手机输入框背景框
     * @param isVisible
     */
    private void setPhoneTipsVisible(boolean isVisible) {
        if(isVisible){
            showSnackBar(llParent,getString(R.string.account_error_tips));
        }
        rlLoginPhone.setBackgroundDrawable(getResources().getDrawable(isVisible == true ? R.drawable.format_error_shape_icon : R.color.transparent));
    }

    /**
     *   设置验证码错误提示 并更改验证码输入框背景
     * @param isVisible
     */
    private void setCodeTipsVisible(boolean isVisible) {
        if(isVisible){
            showSnackBar(llParent,getString(R.string.code_error_tips));
        }
        llLoginCode.setBackgroundDrawable(getResources().getDrawable(isVisible == true ? R.drawable.format_error_shape_icon : R.color.transparent));
    }

    /**
     *  设置验证码背景和字体颜色
     * @param isFormatRight
     */
    public void setCode(boolean isFormatRight) {
        if (isFormatRight) {
            tvGetCode.setBackgroundDrawable(WYRecorderApp.getContext().getResources().getDrawable(R.drawable.shape_get_code_bg));
            tvGetCode.setTextColor(getResources().getColor(R.color.white));
            tvGetCode.setEnabled(true);
        } else {
            tvGetCode.setBackgroundDrawable(WYRecorderApp.getContext().getResources().getDrawable(R.drawable.shape_un_code_bg));
            tvGetCode.setTextColor(getResources().getColor(R.color.white));
            tvGetCode.setEnabled(false);
        }
    }

    /**
     *    设置登录按钮背景和字体颜色
     * @param isFormatRight
     */
    public void setLoginBtn(boolean isFormatRight) {
        if (isFormatRight) {
            btnLogin.setBackgroundDrawable(WYRecorderApp.getContext().getResources().getDrawable(R.drawable.shape_login_btn_bg));
            btnLogin.setTextColor(WYRecorderApp.getContext().getResources().getColor(R.color.white));
        } else {
            btnLogin.setBackgroundDrawable(WYRecorderApp.getContext().getResources().getDrawable(R.drawable.shape_unlogin_btn_bg));
            btnLogin.setTextColor(WYRecorderApp.getContext().getResources().getColor(R.color.bar_text_selected));
        }
    }

    /**
     *  清除焦点 并消失软键盘
     * @param et
     */
    private void clearInputBg(EditText et){
        ((ViewGroup)et.getParent()).setFocusable(true);
        ((ViewGroup)et.getParent()).setFocusableInTouchMode(true);
        ((ViewGroup)et.getParent()).requestFocus();
        Utils.hiddenKeyBoard(this);
    }
    @OnClick({R.id.btnLogin, R.id.tvGetCode ,R.id.tvLoginProtocol} )
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                if(isPasswordFormatRight && watcher.isFullPhone()
                        && etLoginPhone.getText().toString().replaceAll("\\s*", "").matches(Constants.PHONE_FORMAT)) {
                    goToLogin();
                }else{
                    if(etLoginPhone.isFocused()){
                        clearInputBg(etLoginPhone);
                    }else if(etLoginCode.isFocused()){
                        clearInputBg(etLoginCode);
                    }
                }
                break;
            case R.id.tvGetCode:
                if(etLoginPhone.getText().toString().replaceAll("\\s*", "").matches(Constants.PHONE_FORMAT)) {
                    if (isNeedServiceCode) {
                        dialog = new MyAlertView.Builder(this).creatImgVerificationCode(phoneNum, this);
                    } else {
                        sendSMSCodeMobile();
                    }
                }else{
                    showSnackBar(llParent,getString(R.string.account_error_tips));
                }
                break;
            case R.id.tvLoginProtocol:
                Bundle bundle = new Bundle();
                bundle.putString("url", API.HOST + API.YUER_AGREEMENT);
                jumpToActivity(SubjectActivity.class, bundle);
                break;
        }

    }

    /**
     * 发送短信验证码
     */
    private void sendSMSCodeMobile() {
        phoneNum = etLoginPhone.getText().toString();
        phoneNum = phoneNum.replaceAll("\\s*", "");
        Map<String, String> map = new HashMap<>();
        map.put("mobile", phoneNum);
        map.put("type", "4");//1:发送注册的验证码2:发送找回密码的验证码4快捷登录验证码5第三方登录验证码
        if (isNeedServiceCode) {//2两小时获取验证码超过3次,需要输入图片验证码
            map.put("code", imputServicerCode);
        }
        sendHttpRequest(API.SEND_SMS_CODE_MOBILE, map);
    }

    private void goToLogin() {
        phoneNum = etLoginPhone.getText().toString();
        phoneNum = phoneNum.replaceAll("\\s*", "");
        password = etLoginCode.getText().toString();
        if (!phoneNum.matches(Constants.PHONE_FORMAT)) {//校验手机号码
            showToast(getResources().getString(R.string.phone_format_is_not_correct));
            return;
        }
        NIMHelper.getInstance().logout();

        Map<String, String> map = new HashMap();
        map.put("username", phoneNum);
        map.put("source", "2");
        map.put("checkCode", password);
        map.put("type", "2");
        sendHttpRequest(API.LOGIN, map);
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        switch (method) {
            case API.LOGIN:
                loginSuccess(object);
                timeOut();
                jumpToActivity(MainActivity.class);
                break;
            case API.SEND_SMS_CODE_MOBILE:
                if (dialog != null) {
                    dialog.dismiss();
                }
                timeStart();
                showToast(getResources().getString(R.string.code_is_sended));
                break;
        }
    }

    @Override
    public void onError(String errMsg, String method) {
        super.onError(errMsg, method);
        showToast(getResources().getString(R.string.noNeteork));
    }

    @Override
    public void onFaild(JSONObject object, String method) {
        super.onFaild(object, method);
        try {
            switch (method) {
                case API.LOGIN:
                    if (object.has("result")) {
                        showToast(object.getString("result").toString());
                    } else {
                        showToast(getResources().getString(R.string.login_fail));
                    }
                    break;
                case API.SEND_SMS_CODE_MOBILE:
                    if (object.getInt("code") == 10) {//2两小时获取验证码超过3次,需要输入图片验证码
                        isNeedServiceCode = true;
                        dialog = new MyAlertView.Builder(this).creatImgVerificationCode(phoneNum, this);
                    } else if (object.getInt("code") == 6) {//服务器验证码错误
                        dialogRlServiceCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_rectangle_corner_solid_06));
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                dialogRlServiceCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_rectangle_corner_solid_05));
                                ((EditText) dialogEtServiceCode).setText("");
                                AsyncImage.loadYZM(API.HOST + API.IMAGE_CODE_REGISTER + phoneNum, (ImageView) dialogIvServiceCode);
                            }
                        }, 1100);
                        dialogRlServiceCode.startAnimation(animiationShaking);
                        dialogTvYes.setEnabled(false);
                        dialogTvYes.setBackgroundDrawable(WYRecorderApp.getContext().getResources().getDrawable(R.drawable.dialog_button_pri));
                        ((TextView) dialogTvYes).setTextColor(WYRecorderApp.getContext().getResources().getColor(R.color.hall_live_item_bg));
                    } else {
                        if (object.has("result")) {
                            showToast(object.getString("result").toString());
                        }
                    }
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录成功后
     *
     * @param object
     */
    private void loginSuccess(final JSONObject object) {
        try {
            User user = new Gson().fromJson(object.getString("object"), User.class);
			if(user != null)
			{
                UserProxy.setUser(user);
				NIMHelper.getInstance().login(user.getShouboAccid(),user.getId());
			}
            this.setResult(RESULT_OK);
            Utils.hiddenKeyBoard(this);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 100);
        } catch (JSONException e) {
            e.printStackTrace();
            finish();
        }
    }


    @Override
    public void doPositive(String verificationCode) {
        if (verificationCode == null || TextUtils.isEmpty(verificationCode)) {
            showToast("请输入图片验证码");
            return;
        }
        imputServicerCode = verificationCode;
        sendSMSCodeMobile();
    }

    @Override
    public void doNegative() {

    }

    @Override
    public void changeView(View view1, View view2, View view3, View view4) {
        dialogRlServiceCode = view1;
        dialogTvYes = view2;
        dialogIvServiceCode = view3;
        dialogEtServiceCode = view4;
    }

    private void timeOut() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    /**
     * 倒计时开始
     */
    private void timeStart() {
        if(timer == null){
            timer = new Timer();
        }
        if (myHandler == null) {
            myHandler = new MyHandler();
        }
        if (task != null){
            /*maybe the previous timertask have not been cancelled*/
            task.cancel();
            task = null;
        }
        task = new MyTimerTask();
        totalTime = 60;
        timer.schedule(task, 0, 1000);
        tvGetCode.setText(totalTime + "s");
    }

    @Override
    public void setValue(boolean isWholePhoneNum) {
        setCode(isWholePhoneNum);
        if(isPasswordFormatRight && isWholePhoneNum){
            setLoginBtn(true);
        }else{
            setLoginBtn(false);
        }
    }


    public class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            totalTime--;
            myHandler.sendEmptyMessage(0);
        }
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (totalTime > 0) {
                tvGetCode.setText(totalTime + "s");
                setCode(false);
                tvGetCode.setEnabled(false);
            } else {
                tvGetCode.setEnabled(true);
                setCode(true);
                tvGetCode.setText(toObtain);
                timeOut();
            }
        }
    }
}

